package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"meituan-waimai/models/mysql"
	"meituan-waimai/pkg"

	"meituan-waimai/meituanrpc/internal/svc"
	"meituan-waimai/meituanrpc/meituanrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type MerchantRealNameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewMerchantRealNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MerchantRealNameLogic {
	return &MerchantRealNameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *MerchantRealNameLogic) MerchantRealName(in *meituanrpc.MerchantRealNameRequest) (*meituanrpc.MerchantRealNameResponse, error) {
	// todo: add your logic here and delete this line
	var merchant mysql.Merchant
	mysql.DB.Where("id = ?", in.MerchantId).First(&merchant)
	if merchant.ID == 0 {
		return nil, fmt.Errorf("商户不存在，请前往注册")
	}
	var merchantRealName mysql.MerchantRealName
	mysql.DB.Where("merchant_id = ?", in.MerchantId).First(&merchantRealName)
	if merchantRealName.ID != 0 {
		return nil, fmt.Errorf("当前商户已认证，不可重复认证")
	}
	res := pkg.RealName(in.IdCard, in.Name)
	fmt.Println(res)
	if res.ErrorCode != 0 {
		return nil, fmt.Errorf("认证接口调用失败")
	}
	if res.Result.Isok != true {
		return nil, fmt.Errorf("身份信息不匹配，实名失败")
	}
	merchantRealName = mysql.MerchantRealName{
		Model:      gorm.Model{},
		MerchantId: in.MerchantId,
		IdCard:     in.IdCard,
		Name:       in.Name,
	}
	mysql.DB.Create(&merchantRealName)
	return &meituanrpc.MerchantRealNameResponse{}, nil
}
